--[[-------------------------------------------------------------------------
  Copyright (c) 2006, Trond A Ekseth
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are
  met:

      * Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
      * Redistributions in binary form must reproduce the above
        copyright notice, this list of conditions and the following
        disclaimer in the documentation and/or other materials provided
        with the distribution.
      * Neither the name of Atropine nor the names of its contributors
        may be used to endorse or promote products derived from this
        software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------]]

local B, L = {}
local G = getfenv(0)
local addon = DongleStub('Dongle-Beta0'):New('Atropine')
local print = function(...) addon:Print(...) end
local printf = function(...) addon:PrintF(...) end
local function sortedpairs(t,comparator)
	local sortedKeys = {}
	table.foreach(t, function(k,v) table.insert(sortedKeys,k) end)
	table.sort(sortedKeys,comparator)
	local i = 0
	local function _f(_s,_v)
		i = i + 1
		local k = sortedKeys[i]
		if (k) then
			return k,t[k]
		end
	end
	return _f
end
local CashString = function(money)
	if(not money) then return end

	local str, sep = "", " "
	local cS, cC, cG = "|cffC0C0C0", "|cffCC9900", "|cffFFFF66"

	if(money == 0) then return cC..money..sep..COPPER end

	local gold = math.floor(money / (COPPER_PER_SILVER * SILVER_PER_GOLD))
	local silver = math.floor((money - (gold * COPPER_PER_SILVER * SILVER_PER_GOLD)) / COPPER_PER_SILVER)
	local copper = math.fmod(money, COPPER_PER_SILVER)

	if(gold > 0) then str = cG..gold..sep..GOLD end
	if(silver > 0) then str = str..(str ~= "" and sep or "")..cS..silver..sep..SILVER end
	if(copper > 0) then str = str..(str ~= "" and sep or "")..cC..copper..sep..COPPER end

	return str
end
local vars = {
	["Anesthetic Poison"] = "21835;8925-1:3777-4:5173-1",
	["Crippling Poison"] = "3775;3171-1:2930-1 3776;8925-1:8923-3",
	["Deadly Poison"] = "2892;3372-1:5173-1 2893;3372-1:5173-2 8984;8925-1:5173-3 8985;8925-1:5173-5 20844;8925-1:5173-7 22053;8925-1:2931-1 22054;8925-1:2931-1:5173-1",
	["Instant Poison"] = "6947;3371-1:2928-1 6949;3372-1:2928-3 6950;3372-1:8924-1 8926;8925-1:8924-2 8927;8925-1:8924-3 8928;8925-1:8924-4 21927;8925-1:2931-1:8924-1",
	["Mind-numbing Poison"] = "5237;3371-1:2930-1:2928-1 6951;3372-1:2930-4:2928-4 9186;8925-1:8923-2:8924-2",
	["Wound Poison"] = "10918;3372-1:2930-1:5173-1 10920;3372-1:2930-1:5173-2 10921;8925-1:8923-1:5173-2 10922;8925-1:8923-2:5173-2 22055;8925-1:8923-3:5173-3",
	["Flash Powder"] = "5140;5140-1",
}
addon.defaults = {
	char = {
		db = 1,
		poisons = {},
		auto = {},
	}
}
addon.locale = {}
addon.class = {}

function addon:Initialize()
	self.db = self:InitializeDB("AtropineDB", self.defaults)
	self.frame = self:createFrame("AtropineFrame", true)

	self.frame:SetPoint("TOP", MerchantFrame, "BOTTOM", 15, 0)
end

function addon:Enable()
	L = AtropineLocale

	local class = select(2, UnitClass"player")
	if(class ~= "ROGUE") then
		DisableAddOn("Atropine")
		return print(L["Disabled"])
	end

	self:RegisterEvent("MERCHANT_SHOW", "merchantShow")
	self:RegisterEvent("MERCHANT_CLOSED", "merchantClosed")
	self:RegisterEvent("PLAYER_LEVEL_UP", "playerLevelUp")
	self:registerEvents()

	if(self.db.char.cache ~= UnitLevel("player")) then
		self:registerEvents()
	else
		local b, cache = 1, self.db.char.poisons
		for p, v in sortedpairs(cache) do
			self.frame[b] = self.class.button:new(p, v.texture, b)
			b = b + 1
		end
	end
end

function addon:registerEvents()
	self:RegisterEvent("TRADE_SKILL_UPDATE", "createCache")
end

function addon:GetID(item)
	if type(iem) == "number" then return item
	elseif type(item) == "string" then
		local _, _, id = string.find(item, "item:(%d+):")
		if id then return tonumber(id) end
	end
end

function addon:IsPoisonVendor()
	for m=1,GetMerchantNumItems() do
		local link = GetMerchantItemLink(m)
		if(self:GetID(link) == 5140) then return true end
	end
	return false
end

function addon:createCache()
	self:UnregisterEvent("TRADE_SKILL_UPDATE")

	if(not GetTradeSkillLine() == L["Poisons"]) then return end

	print("KEKKE")

	local cache, temp, mats, name, level, texture, i, b = {}

	b = 1
	for poison, ranks in sortedpairs(vars) do
		temp = {}
		i = 1

		for p, r in string.gmatch(ranks, "(%S+);(%S+)") do
			name, _, _, level, _, _, _, _, _, texture  = GetItemInfo(p)
			mats = {}

			for m, c in string.gmatch(r, "(%d+)-(%d)") do
				mats[tonumber(m)] = tonumber(c)
			end

			if(name and level <= UnitLevel("player")) then
				temp[i] = {
					name = name,
					texture = texture,
					level = level,
					rank = i,
					id = tonumber(p),
					mats = mats,
				}
			end
			i = i + 1
		end

		local s = #temp
		if(s >= 1) then
			cache[poison] = temp[s]
			self.db.char.poisons = cache -- We set it here, so we can fetch ranks at this point.
			self.frame[b] = self.class.button:new(poison, texture, b)
			b = b + 1
		end
	end

	self.db.char.cache = UnitLevel("player")
end

function addon:merchantShow()
	if(self:IsPoisonVendor()) then
		self.frame:Show()

		if(not IsShiftKeyDown() and self.db.char.cache == UnitLevel"player") then
			for k,v in pairs(self.db.char.auto) do
				if(v.e) then
					self:add(k, v.q, true)
				end
			end
			self:buy(true)
		end
	end
end

function addon:merchantClosed()
	if(self.frame:IsShown()) then
		self.frame:Hide()
	end
end

function addon:playerLevelUp(event, level)
	self:registerEvents()
end

function addon:buy(refill)
	for r, c in pairs(B) do
		for m=1, GetMerchantNumItems() do
			local name, _, price, num = GetMerchantItemInfo(m)
			local link = GetMerchantItemLink(m)
			if(self:GetID(link) == r) then
				local t = ((r ~= 5140 and refill and c - GetItemCount(r)) or c)/num
				while(t > 0) do
					local b = math.min(t, GetMerchantItemMaxStack(m))
					BuyMerchantItem(m, b)
					t = t - b
				end
				B[r] = nil
			end
		end
	end
end

function addon:getFullName(poison)
	local sc = self.db.char.poisons[poison]
	if(sc) then
		return sc.name
	else
		return poison
	end
end

function addon.decimalToRoman(d)
	local r = ""
	if(d <= 0) then return end
	while(d ~= 0) do
		if(d >= 10) then
			d = d - 10;r = r.."X"
		elseif(d == 9) then
			d = d - 9;r = r.."IX"
		elseif(d >= 5) then
			d = d - 5;r = r.."V"
		elseif(d == 4) then
			d = d - 4;r = r.."IV"
		elseif(d >= 1) then
			d = d - 1;r = r.."I"
		end
	end
	return r
end

function addon:getCost(poison, amount, refill)
	poison = self.db.char.poisons[poison]
	amount = (refill and amount - GetItemCount(poison.id)) or amount
	local total = 0

	if(amount <= 0) then return CashString(total) end

	for r, q in pairs(poison.mats) do
		for m=1, GetMerchantNumItems() do
			local _, _, price, num = GetMerchantItemInfo(m)
			local link = self:GetID(GetMerchantItemLink(m))

			if(link == r) then
				total = total + ((q/num)*amount)*price
			end
		end
	end

	return CashString(total)
end

function addon:add(poison, amount, refill)
	poison = self.db.char.poisons[poison]
	amount = (refill and amount - GetItemCount(poison.id)) or amount

	if(amount > 0) then
		local link = select(2, GetItemInfo(poison.id))
		printf(L["Buying"], amount, link)

		for r, q in pairs(poison.mats) do
			q = amount * q
			B[r] = (B[r] or 0) + q
		end
	end
end

function addon:getRefill(poison)
	local v = self.db.char.auto[poison]
	if(not v) then return nil end
	return v.e, v.q
end

function addon:updateRefillV(poison, q)
	if(not self.db.char.auto[poison]) then self.db.char.auto[poison] = {} end
	self.db.char.auto[poison].q = q
end

function addon:updateRefillS(poison, update)
	if(not self.db.char.auto[poison]) then self.db.char.auto[poison] = {q = 0} end
	self.db.char.auto[poison].e = update
end

G["Atropine"] = addon
